#include "imagewindow.h"
#include "ui_imagewindow.h"
#include <vector>
#include <QDebug>
using namespace cv;
using namespace std;

ImageWindow::ImageWindow(QWidget *parent) :
    QLabel(parent),
    ui(new Ui::ImageWindow)
{
    ui->setupUi(this);
    // 图片左翻
    connect(ui->btnLeft, &QPushButton::clicked, this, [=](){
        if (--m_curIndex < 0) m_curIndex = m_Imgs.size() - 1;
        showImg(m_curIndex);
    });
    // 图片右翻
    connect(ui->btnRight, &QPushButton::clicked, this, [=](){
        if (++m_curIndex > (int)m_Imgs.size() - 1) m_curIndex = 0;
        showImg(m_curIndex);
    });
    // 图片数量改变或者索引改变时，更新labIndex
    connect(this, &ImageWindow::indexChange, this, [=](){
        if (m_Imgs.size() == 0) {
            ui->labIndex->setText("0/0");
        }
        else {
            QString str = QString("%1/%2").arg(m_curIndex + 1).arg(m_Imgs.size());
            ui->labIndex->setText(str);
        }
    });
}

ImageWindow::~ImageWindow()
{
    delete ui;
}

void ImageWindow::showImg(int index) {
    if (index < 0 || index >= (int)m_Imgs.size()) return;
    cv::Mat img;
    cvtColor(m_Imgs[index], img, cv::COLOR_BGR2RGB);
    QImage qImg((const uchar*)img.data, img.cols, img.rows, img.cols * img.channels(), QImage::Format_RGB888);
    ui->labImg->setScaledContents(true);
    ui->labImg->setPixmap(QPixmap::fromImage(qImg));
    emit this->indexChange();
}

void ImageWindow::clearImgs() {
    ui->labImg->clear();
    m_curIndex = 0;
    m_Imgs.clear();
    emit this->indexChange();
}

void ImageWindow::addImgs(deque<cv::Mat> imgs) {
    for (cv::Mat img : imgs) {
        m_Imgs.push_back(img);
        // 检查是否超出容量，若超出则把第一个出队
        if (m_capcity > 0 && (int)m_Imgs.size() > m_capcity)
            m_Imgs.pop_front();
    }
    emit this->indexChange();
}

void ImageWindow::addImg(cv::Mat img) {
    m_Imgs.push_back(img);
    if (m_capcity > 0 && (int)m_Imgs.size() > m_capcity)
        m_Imgs.pop_front();
    emit this->indexChange();
}

void ImageWindow::hideBtn() {
    ui->btnLeft->hide();
    ui->btnRight->hide();
    ui->labIndex->hide();
}

void ImageWindow::setCapcity(int cap) {
    m_capcity = cap;
}
